<template>
  <view class="container">
    <!-- 状态栏 -->
    <view class="status-bar bg-white">
      <view class="flex items-center">
        <uni-icons type="wifi-filled" size="28" color="#333333" class="mr-2"></uni-icons>
        <uni-icons type="battery" size="28" color="#333333"></uni-icons>
      </view>
    </view>

    <!-- 导航栏 -->
    <view class="nav-bar bg-white">
      <text class="text-lg font-medium">点餐</text>
    </view>

    <!-- 搜索栏 -->
    <view class="search-bar bg-white">
      <view class="search-input">
        <uni-icons type="search" size="16" color="#999999"></uni-icons>
        <input type="text" placeholder="搜索菜品" v-model="searchText" />
      </view>
    </view>

    <!-- 分类和菜品列表 -->
    <view class="menu-content">
      <!-- 左侧分类列表 -->
      <scroll-view scroll-y class="category-list">
        <view v-for="(category, index) in categories" :key="category.id" class="category-item"
          :class="{ active: currentCategory === index }" @tap="switchCategory(index)">
          <text>{{ category.name }}</text>
        </view>
      </scroll-view>

      <!-- 右侧菜品列表 -->
      <scroll-view scroll-y class="dish-list" @scroll="onScroll">
        <view class="dish-category" v-for="category in categories" :key="category.id">
          <view class="category-title">{{ category.name }}</view>
          <view class="dish-grid">
            <view class="dish-item" v-for="dish in category.dishes" :key="dish.id" @click="goToDishDetail(dish)">
              <image :src="dish.image" mode="aspectFill" class="dish-image"></image>
              <view class="dish-info">
                <text class="dish-name">{{ dish.name }}</text>
                <view class="dish-tags">
                  <view class="dish-tag signature" v-if="dish.isSignature">招牌</view>
                  <view class="dish-tag spicy" v-if="dish.spicyLevel">{{ dish.spicyLevel }}</view>
                  <view class="dish-tag discount" v-if="dish.discount">{{ dish.discount }}</view>
                </view>
                <text class="dish-desc">{{ dish.description }}</text>
                <view class="dish-bottom">
                  <text class="dish-price">¥{{ dish.price }}</text>
                  <view class="quantity-control" @click.stop>
                    <uni-icons v-if="getCartQuantity(dish.id) > 0" type="minus-filled" size="24" color="#3db87f" @click="decreaseQuantity(dish)"></uni-icons>
                    <text v-if="getCartQuantity(dish.id) > 0" class="quantity-text">{{ getCartQuantity(dish.id) }}</text>
                    <uni-icons type="plus-filled" size="24" color="#3db87f" @click="openSpecPopup(dish)"></uni-icons>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 购物车悬浮按钮 -->
    <view class="cart-bar" v-if="totalQuantity > 0">
      <view class="cart-info" @tap="openCartPopup">
        <view class="cart-icon-container">
          <uni-icons type="cart-filled" size="44" color="#3db87f"></uni-icons>
          <view class="cart-badge">{{ totalQuantity }}</view>
        </view>
        <view class="price-info">
          <text class="total-price">¥{{ totalPrice }}</text>
        </view>
      </view>
      <view class="cart-action" :class="{ 'cart-action-disabled': !isBusinessHours, 'cart-action-active': isBusinessHours }" @tap="isBusinessHours ? submitOrder() : null">
        <text>{{ isBusinessHours ? '去结算' : '已打烊' }}</text>
      </view>
    </view>

    <!-- 购物车弹出层 -->
    <uni-popup ref="cartPopup" type="bottom" :mask-click="true" :safe-area="false" style="z-index: 9999;">
      <view class="cart-popup">
        <view class="cart-popup-header">
          <text class="cart-popup-title">已选{{ totalQuantity }}份商品</text>
          <view class="cart-popup-clear" @tap="clearCart">
            <uni-icons type="trash" size="16" color="#999"></uni-icons>
            <text>清空</text>
          </view>
        </view>
        
        <scroll-view class="cart-popup-content" scroll-y>
          <view class="cart-item" v-for="item in cartItemsWithDetails" :key="item.dishId">
            <image :src="item.image" mode="aspectFill" class="cart-item-image"></image>
            <view class="cart-item-info">
              <view class="cart-item-details">
                <text class="cart-item-name">{{ item.name }}</text>
                <view class="cart-item-specs" v-if="item.spec || item.spicy || item.flavor">
                  <text>{{ [item.spec, item.spicy, item.flavor].filter(Boolean).join('·') }}</text>
                </view>
                <text class="cart-item-price">¥{{ item.price }}</text>
              </view>
              <view class="cart-item-quantity">
                <uni-icons type="minus-filled" size="24" color="#3db87f" @click="decreaseQuantity({id: item.dishId})"></uni-icons>
                <text class="quantity-text">{{ item.quantity }}</text>
                <uni-icons type="plus-filled" size="24" color="#3db87f" @click="increaseCartQuantity(item)"></uni-icons>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </uni-popup>

    <!-- 添加规格选择弹出层 -->
    <spec-popup 
      ref="specPopupRef"
      :dish="selectedDish"
      :initial-quantity="getCartQuantity(selectedDish.id) || 1"
      @confirm="handleSpecConfirm"
      @close="handleSpecClose"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import SpecPopup from '@/components/SpecPopup.vue';

// 搜索文本
const searchText = ref('');

// 在script部分添加类型定义
interface Dish {
  id: number;
  name: string;
  description: string;
  price: number;
  image: string;
  isSignature?: boolean;
  discount?: string;
  spicyLevel?: string;
}

// 然后修改categories的类型
const categories = ref<{
  id: number;
  name: string;
  dishes: Dish[];
}[]>([
  {
    id: 1,
    name: '热销推荐',
    dishes: [
      {
        id: 1,
        name: '北京烤鸭',
        description: '店长推荐 • 本周特惠',
        price: 198,
        isSignature: true,
        discount: '本周特惠',
        image: 'https://p9-bot-workflow-sign.byteimg.com/tos-cn-i-mdko3gqilj/31e44832a9c645df913ec4299773a51a.png~tplv-mdko3gqilj-image.png?rk3s=c8fe7ad5&x-expires=1773850158&x-signature=J52YknSQKiBo2bPtj6kedWUQkK8%3D'
      },
      {
        id: 2,
        name: '麻婆豆腐',
        description: '川菜代表 • 中辣',
        price: 48,
        spicyLevel: '中辣',
        image: 'https://p26-bot-workflow-sign.byteimg.com/tos-cn-i-mdko3gqilj/38148bf503e7494cbf4a4e1c4115bc03.png~tplv-mdko3gqilj-image.png?rk3s=c8fe7ad5&x-expires=1773850697&x-signature=ciyEP%2BdtyeM2IO6dhTfJUdxboyw%3D'
      }
    ]
  },
  {
    id: 2,
    name: '粤式点心',
    dishes: [
      {
        id: 3,
        name: '虾饺',
        description: '晶莹剔透 • 鲜美多汁',
        price: 38,
        image: 'https://images.unsplash.com/photo-1563245372-f21724e3856d?w=120&q=80'
      }
    ]
  },
  {
    id: 3,
    name: '粤式火锅',
    dishes: [
      {
        id: 4,
        name: '海鲜火锅',
        description: '新鲜海鲜 • 配料丰富',
        price: 288,
        image: 'https://images.unsplash.com/photo-1569718212165-3a8278d5f624?w=120&q=80'
      }
    ]
  }
]);

// 当前选中的分类
const currentCategory = ref(0);

// 购物车数据
const cartItems = ref<{ dishId: number; quantity: number; spec?: string; spicy?: string; flavor?: string }[]>([]);

// 切换分类
const switchCategory = (index: number) => {
  currentCategory.value = index;
};

// 获取购物车中某个菜品的数量
const getCartQuantity = (dishId: number): number => {
  const item = cartItems.value.find(item => item.dishId === dishId);
  return item ? item.quantity : 0;
};

// 计算购物车总价和总数量
const calculateTotal = () => {
  // 总价和总数量已经通过computed属性计算，
  // 这里可以添加其他需要的逻辑，比如保存到本地存储
  uni.setStorageSync('cartItems', cartItems.value);
};

// 减少购物车中的数量
const decreaseQuantity = (dish: any) => {
  const index = cartItems.value.findIndex(item => item.dishId === dish.id);
  if (index !== -1) {
    if (cartItems.value[index].quantity > 1) {
      cartItems.value[index].quantity--;
    } else {
      cartItems.value.splice(index, 1);
    }
    // 更新总价和总数量
    calculateTotal();
  }
};

// 计算购物车总数量
const totalQuantity = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0);
});

// 计算购物车总价
const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => {
    const dish = categories.value
      .flatMap(category => category.dishes)
      .find(dish => dish.id === item.dishId);
    return total + (dish ? dish.price * item.quantity : 0);
  }, 0);
});

// 滚动处理
const onScroll = (e: any) => {
  // 可以根据滚动位置更新当前分类
};

// 跳转到购物车页面
const goToCart = () => {
  uni.switchTab({
    url: '/pages/cart/index'
  });
};

// 添加跳转到菜品详情页的方法
const goToDishDetail = (dish: any) => {
  uni.navigateTo({
    url: '/pages/menu/detail',
    success: (res) => {
      // 通过eventChannel向详情页传递数据
      res.eventChannel.emit('dishDetail', dish);
    }
  });
};

// 页面显示时更新购物车数据
onMounted(() => {
  // 从本地存储获取购物车数据
  const storedCartItems = uni.getStorageSync('cartItems') || [];
  cartItems.value = storedCartItems;
  
  // 更新总价和总数量
  calculateTotal();
  
  // 检查营业时间
  checkBusinessHours();
});

// 规格选择相关数据
const selectedDish = ref<Dish>({} as Dish);
const specPopupRef = ref<any>(null);

// 打开规格选择弹窗
const openSpecPopup = (dish: Dish) => {
  selectedDish.value = dish;
  specPopupRef.value.open();
};

// 处理规格确认
const handleSpecConfirm = (data: any) => {
  // 查找是否已存在相同规格的商品
  const existingItemIndex = cartItems.value.findIndex((item: any) => 
    item.dishId === selectedDish.value.id && 
    item.spec === data.spec && 
    item.spicy === data.spicy && 
    item.flavor === data.flavor
  );
  
  if (existingItemIndex !== -1) {
    // 如果已存在，设置数量
    cartItems.value[existingItemIndex].quantity = data.quantity;
  } else {
    // 如果不存在，添加新项
    cartItems.value.push({
      dishId: selectedDish.value.id,
      quantity: data.quantity,
      spec: data.spec,
      spicy: data.spicy,
      flavor: data.flavor
    });
  }
  
  // 计算总价和总数量
  calculateTotal();
  
  // 显示提示
  uni.showToast({
    title: '已加入购物车',
    icon: 'success'
  });
};

// 处理规格弹窗关闭
const handleSpecClose = () => {
  // 可以在这里处理弹窗关闭后的逻辑
};

// 添加营业时间判断
const isBusinessHours = ref(true); // 默认为营业中

// 检查是否在营业时间内
const checkBusinessHours = () => {
  const now = new Date();
  const hours = now.getHours();
  // 假设营业时间为10:00-22:00
  isBusinessHours.value = hours >= 10 && hours < 22;
};

// 提交订单
const submitOrder = () => {
  if (totalQuantity.value > 0) {
    // 获取现有订单
    const existingOrders = uni.getStorageSync('orders') || [];
    
    // 检查是否已有待支付的订单
    const pendingOrderIndex = existingOrders.findIndex((order: any) => order.status === '待支付');
    
    // 准备新的菜品数据
    const newDishes = cartItemsWithDetails.value.map(item => ({
      id: item.dishId,
      name: item.name,
      price: item.price,
      quantity: item.quantity,
      image: item.image
    }));
    
    if (pendingOrderIndex !== -1) {
      // 如果已有待支付订单，更新它
      existingOrders[pendingOrderIndex].dishes = newDishes;
      existingOrders[pendingOrderIndex].totalPrice = totalPrice.value;
      existingOrders[pendingOrderIndex].orderTime = formatDate(new Date());
    } else {
      // 如果没有待支付订单，创建新订单
      const newOrder = {
        orderNumber: generateOrderNumber(),
        status: '待支付',
        orderTime: formatDate(new Date()),
        totalPrice: totalPrice.value,
        remark: '',
        isCurrent: true,
        dishes: newDishes
      };
      
      // 添加新订单
      existingOrders.unshift(newOrder);
    }
    
    // 保存到本地存储
    uni.setStorageSync('orders', existingOrders);
    
    // 跳转到订单页面
    uni.switchTab({
      url: '/pages/order/index'
    });
  } else {
    uni.showToast({
      title: '请先添加菜品',
      icon: 'none'
    });
  }
};

// 生成订单号
const generateOrderNumber = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const random = Math.floor(Math.random() * 10000).toString().padStart(5, '0');
  return `${year}${month}${day}${random}`;
};

// 格式化日期
const formatDate = (date: Date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 添加折扣相关计算属性
const hasDiscount = computed(() => {
  // 这里可以根据实际情况判断是否有折扣
  return false;
});

const originalPrice = computed(() => {
  // 这里可以计算原价
  return (totalPrice.value * 1.2).toFixed(2);
});

// 添加新的ref
const cartPopup = ref<any>(null);

// 添加打开购物车弹窗的方法
const openCartPopup = () => {
  cartPopup.value.open();
};

// 添加清空购物车的方法
const clearCart = () => {
  uni.showModal({
    title: '提示',
    content: '确定要清空购物车吗？',
    success: (res) => {
      if (res.confirm) {
        cartItems.value = [];
        calculateTotal();
        cartPopup.value.close();
      }
    }
  });
};

// 在script部分添加新的接口定义
interface CartItem {
  dishId: number;
  name: string;
  price: number;
  image: string;
  quantity: number;
  spec?: string;
  spicy?: string;
  flavor?: string;
}

// 修改计算属性的返回类型
const cartItemsWithDetails = computed<CartItem[]>(() => {
  return cartItems.value.map(item => {
    const dish = categories.value
      .flatMap(category => category.dishes)
      .find(dish => dish.id === item.dishId);
    return {
      dishId: item.dishId,
      name: dish?.name || '',
      price: dish?.price || 0,
      image: dish?.image || '',
      quantity: item.quantity,
      spec: item.spec,
      spicy: item.spicy,
      flavor: item.flavor
    };
  });
});

// 直接增加购物车中商品数量的方法
const increaseCartQuantity = (item: CartItem) => {
  const cartItem = cartItems.value.find(i => i.dishId === item.dishId);
  if (cartItem) {
    cartItem.quantity++;
    calculateTotal();
  }
};
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f7f7f7;
  display: flex;
  flex-direction: column;
}

.status-bar {
  height: 44px;
  padding: 0 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: sticky;
  top: 0;
  z-index: 100;
}

.nav-bar {
  height: 44px;
  padding: 0 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: sticky;
  top: 44px;
  z-index: 100;
  border-bottom: 1px solid #f0f0f0;
}

.search-bar {
  padding: 10px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.search-input {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 16px;
  padding: 8px 12px;
}

.search-input input {
  flex: 1;
  height: 32px;
  margin-left: 8px;
  font-size: 14px;
}

.menu-content {
  display: flex;
  height: calc(100vh - 140px); /* 调整高度，移除分类标签的高度 */
}

.category-list {
  width: 200rpx;
  height: 100%;
  background-color: #f7f7f7;
}

.category-item {
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #333;
  position: relative;

  &.active {
    background-color: #ffffff;
    color: #3db87f;
    font-weight: 500;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 8rpx;
      height: 32rpx;
      background-color: #3db87f;
      border-radius: 0 4rpx 4rpx 0;
    }
  }
}

.dish-list {
  flex: 1;
  height: 100%;
  background-color: #ffffff;
}

.dish-category {
  padding: 20rpx;
}

.category-title {
  font-size: 32rpx;
  font-weight: 500;
  margin-bottom: 20rpx;
}

.dish-grid {
  display: grid;
  grid-template-columns: repeat(1, 1fr);
  gap: 20rpx;
}

.dish-item {
  display: flex;
  padding: 20rpx;
  background-color: #ffffff;
  border-radius: 12rpx;
}

.dish-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
}

.dish-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.dish-name {
  font-size: 30rpx;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.dish-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8rpx;
  margin: 4rpx 0;
}

.dish-tag {
  display: inline-block;
  font-size: 20rpx;
  padding: 4rpx 10rpx;
  border-radius: 8rpx;
  margin-bottom: 4rpx;
  width: auto;
  max-width: 120rpx;
  text-align: center;
}

.dish-tag.signature {
  background-color: #FFF8E1;
  color: #FFA000;
}

.dish-tag.spicy {
  background-color: #FFEBEE;
  color: #F44336;
}

.dish-tag.discount {
  background-color: #E8F5E9;
  color: #4CAF50;
}

.dish-desc {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 16rpx;
}

.dish-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
}

.dish-price {
  font-size: 32rpx;
  color: #3db87f;
  font-weight: 500;
}

.quantity-control {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.quantity-text {
  font-size: 26rpx;
  min-width: 36rpx;
  text-align: center;
}

/* 新的购物车栏样式 */
.cart-bar {
  position: fixed;
  left: 20rpx;
  right: 20rpx;
  bottom: 20rpx;
  height: 96rpx;
  display: flex;
  align-items: center;
  background-color: #ffffff;
  z-index: 90;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  border-radius: 48rpx;
  overflow: visible;
}

.cart-info {
  flex: 1;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
}

.cart-icon-container {
  position: relative;
  margin-right: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 90rpx;
  height: 90rpx;
  transform: translateY(-15rpx);
  margin-bottom: -15rpx;
}

.cart-badge {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  background-color: #FF0000;
  color: white;
  font-size: 20rpx;
  min-width: 32rpx;
  height: 32rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 6rpx;
  font-weight: bold;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
}

.price-info {
  display: flex;
  flex-direction: column;
  margin-left: 10rpx;
}

.total-price {
  color: #3db87f;
  font-size: 30rpx;
  font-weight: 500;
  line-height: 1.2;
}

.delivery-info {
  color: #999;
  font-size: 24rpx;
  line-height: 1.2;
}

.cart-action {
  width: 200rpx;
  height: 100%;
  background-color: #3db87f;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: 500;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
  border-radius: 0 48rpx 48rpx 0;
}

.cart-action.cart-action-active {
  background-color: #3db87f;
  color: white;
  border-radius: 0 48rpx 48rpx 0;
}

.cart-action-disabled {
  background-color: #999;
  border-radius: 0 48rpx 48rpx 0;
}

/* 修改popup组件的样式 */
:deep(.uni-popup) {
  z-index: 9999 !important;
}

:deep(.uni-popup .uni-popup__wrapper) {
  z-index: 10000 !important;
}

:deep(.uni-popup .uni-popup__mask) {
  z-index: 9998 !important;
}

/* 添加购物车弹出层样式 */
.cart-popup {
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  max-height: 60vh;
  display: flex;
  flex-direction: column;
}

.cart-popup-header {
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f5f5f5;
}

.cart-popup-title {
  font-size: 32rpx;
  font-weight: 500;
}

.cart-popup-clear {
  display: flex;
  align-items: center;
  gap: 4rpx;
  color: #999;
  font-size: 24rpx;
}

.cart-popup-content {
  flex: 1;
  padding: 0 30rpx 0 30rpx;
  max-height: calc(60vh - 200rpx);
  overflow-y: auto; /* 确保内容可以滚动 */
}

.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1px solid #f5f5f5;
  margin-right: 20rpx;
}

.cart-item-image {
  width: 100rpx;
  height: 100rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.cart-item-info {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.cart-item-quantity {
  display: inline-flex;
  align-items: center;
  gap: 16rpx;
  min-width: 120rpx; /* 确保加减号区域有固定宽度 */
  margin-right: 40rpx; /* 增加右侧边距，使加减号往左移 */
}

.cart-item-details {
  flex: 1;
  margin-right: 20rpx; /* 增加右侧边距，为加减号腾出更多空间 */
}

.cart-item-name {
  font-size: 28rpx;
  font-weight: 500;
  margin-bottom: 8rpx;
}

.cart-item-specs {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 8rpx;
}

.cart-item-price {
  font-size: 28rpx;
  color: #3db87f;
  font-weight: 500;
}
</style>